<template>

    <div class="payment-payoneer">

        <button @click="doPayBefore()">Credit or Debit card</button>

        <UxDialog :visible="true" :can-close="false" v-show="!!dialog" class="payment-payoneer-dialog">

            <div class="order-payment-close" @click="onClose()"><svg-icon name="dialog-close-medium" /></div>

            <!-- 输入支付信息 -->
            <div class="order-payment-input" v-show="dialog && dialog.substatus == 'input'"
                 v-loading="dialog && dialog.loading">
                <h2>Pay with card</h2>

                <div class="card-code" :ready="ready">
                    <h3>
                        <img src="@/assets/images/payoneer/payoneer-card.png" alt="">
                        <span>Payment card</span>
                    </h3>
                    <div id="paymentNetworks" class="payment-networks-container"></div>
                    <div id="submitBtnContainer" class="card-code-button"><button id="submitBtn">Pay now</button></div>
                </div>

                <!-- 账单地址 -->
                <OrderPaymentPayoneerBilling v-if="dialog" :loading.sync="loading" v-model="addressCurrent"
                                             :tab.sync="addressTab" :save.sync="addressSave"
                                             :forbid.sync="addressForbid" :addressBilling.sync="addressBilling"
                                             :addressList="addressList" :option="option" :approve_code="approve_code" />

                <div class="card-footer">
                    <button type="primary" :disabled="addressForbid" @click="doPayButtonClick()">
                        <svg-icon name="payment-safety" />
                        <span>Pay now</span>
                    </button>
                </div>

                <p>
                    <img src="@/assets/images/payoneer/payoneer-notify.png">
                    <span>Your payment information is securely encrypted with 128-bit SSL.</span>
                </p>

                <UxLoading2 :loading="loading" />
            </div>

            <!-- 请求超时 -->
            <div class="order-payment-timeout" v-show="dialog && dialog.substatus == 'timeout'">
                <figure>
                    <img src="https://img.podpartner.com/static/images-20230202/payment/order-payment-network.png"
                         alt="">
                    <strong>Payment connection has timed out.</strong>
                </figure>
                <button type="primary" @click="doPayBefore()">Try again</button>
            </div>

            <!-- 支付失败 -->
            <div class="order-payment-failure" v-show="dialog && dialog.substatus == 'failure'">
                <figure>
                    <img src="https://img.podpartner.com/static/images-20230202/payment/order-payment-failure.png"
                         alt="">
                    <strong>Payment failed</strong>
                    <span v-text="dialog && dialog.error"></span>
                </figure>
                <button type="primary" @click="onClose()">OK</button>
            </div>

            <!-- 轮询中 -->
            <div class="order-payment-polling" v-show="dialog && dialog.substatus == 'polling'">
                <figure><img src="https://img.podpartner.com/static/images-20230202/order-paying.png"></figure>
                <h4><img src="@/assets/images/pay-loading.gif" alt="" /></h4>
                <p>Paying, please wait patiently</p>
            </div>

            <!-- 检查订单支付状态 -->
            <div class="order-payment-pending" v-show="dialog && dialog.substatus == 'pending'">
                <figure><img src="https://img.podpartner.com/static/images-20230202/order-pending.png"></figure>
                <h4><img src="@/assets/images/pay-pending.gif" alt="" /></h4>
                <p>Payment is being processed. Please do not pay again.</p>
            </div>

        </UxDialog>
    </div>

</template>
<script>
import { mapGetters, mapState } from "vuex";
import PaymentUtils from '@/utils/PaymentUtils.js';
import '@/assets/styles/op-payment-widget-v3.css';

export default {
    name: "OrderPaymentPayoneer",
    props: ["option"],
    data () {
        return {
            dialog: null, // input|timeout|jumpto|polling|failure
            ready: false,
            loading: false,
            payoneer: null,
            approve_code: '',
            addressList: [],
            addressBilling: null,
            addressTab: '',
            addressSave: false,
            addressForbid: false,
            addressCurrent: {
                first_name: '', // string 姓名
                last_name: '', // 名
                country_code: '', // string 国家（国际二字码 标准ISO 3166-2 ）
                country: '', // string 国家名称
                city: '', // string 城市
                state: '', // string  州/省
                district: '', // string 区、县（可对应为adress 2）
                street: '', // string 街道/详细地址（可对应为adress 1）
                email: '', // string 邮箱
                phone: '', // string 电话
                post_code: '', // string 邮编
            }

        };
    },

    computed: {
        ...mapGetters("user", {
            userInfo: "getUserInfo",
        }),
    },

    methods: {

        // 关闭对话框
        onClose () {
            if (!this.dialog) {
                // 没有对话框
            } else if (this.dialog.substatus == 'input') {
                this.dialog = null;
                this.$emit('statusChange', {
                    payment: 'card',
                    action: 'cancel',
                    substatus: 'input',
                    message: 'Close paying windows'
                })
            } else if (this.dialog.substatus == 'timeout') {
                this.dialog = null;
                this.$emit('statusChange', {
                    payment: 'card',
                    action: 'cancel',
                    substatus: 'input',
                    message: 'Close paying windows'
                })
            } else {
                // 如果是支付失败,则返回到当前
                this.dialog.substatus = 'input';
                this.dialog.loading = false;
            }
        },

        // 设置父级状态
        setParentStatus (status) {
            const parent = this.$parent.$parent;
            if (parent) {
                parent.status = status
            }
        },


        // 01.点击按钮，支付前判断
        doPayBefore () {
            // 清空支付数据
            this.dialog = null
            this.$emit('statusChange', {
                payment: 'card',
                action: 'before',
                callback: res => {
                    if (!res) {
                        // 出错了
                    } else {
                        this.setParentStatus('before')
                        this.doOpenPayingDialog()
                    }
                }
            })
        },


        // 打开支付弹窗
        doOpenPayingDialog () {

            const dialog = {
                substatus: 'input', // input|timeout|jumpto|polling|pending|failure
                loading: false,
                error: '',
                verify: null, // 二次验证
                popup: null,
                timeout: new Date().getTime() + 30 * 60 * 1000, // 超时时间为30分钟
            }

            const getPayCode = () => {
                const paycode = { paypal: 1, card: 2, payoneer: 3, wallet: 4 }['payoneer'];

                // const res = await this.$http("Wallet.putRecharge", { amount: value });
                if (this.option.action == 'recharge') {
                    // 钱包充值
                    return this.$http("Wallet.putRecharge", {
                        amount: this.option.amount,
                    })
                } else if (this.option.action == 'batch') {
                    // 批量支付
                    return this.$http("Order.batchPayOrder", {
                        order_code: this.option.codes,
                        payment: paycode,
                    })
                } else {
                    //  单个支付
                    return this.$http("Order.payOrder/" + this.option.codes, { payment: paycode });

                    // if (['localhost:3000', 'zxtest.podpartner.com'].indexOf(location.host) >= 0 && location.href.indexOf('debug=3d')) {
                    //     // 测试3d验证
                    //     // let code = 'xnnnnnnnnnnnn'
                    //     // code = code.replace(/x/g, () => String.fromCharCode(65 + Math.floor(Math.random() * 26)))
                    //     // code = code.replace(/n/g, () => Math.floor(Math.random() * 10));
                    //     return this.$http("Order.payoneerPaySign", { order_code: this.option.codes, order_amount: 999 }).then(res => Promise.resolve({ code: 0, data: { approve_url: res.data.links.self } }))
                    // } else {

                    // }

                    // 测试已经支付
                    // return this.$http("Order.payOrder/S2024022685714845" + code, { payment: paycode });

                }
            }


            // 获取地址列表
            const getAddressList = () => {
                return this.$http("address.search")
            }

            // 获取账单地址
            const getBillingAddress = () => {
                return this.$http("address.getBilling")
            }


            Promise.all([getPayCode(), getAddressList(), getBillingAddress()]).then(res => {

                const [payoneer, address, billing] = res
                const data = payoneer.data || {}
                const elem = document.querySelector('#paymentNetworks')


                if (payoneer.code === 0 && address.code === 0 && billing.code === 0) {

                    if (this.option.action == 'single' && payoneer.data && payoneer.data.state == 1) {
                        // 库存问题
                        this.dialog = null;
                        this.$emit('statusChange', {
                            payment: 'paypal',
                            action: 'stock',
                            stocks: payoneer.data.list || [],
                            message: payoneer.msg
                        })
                    } else {


                        elem && (elem.innerHTML = '')

                        this.timeout = new Date().getTime()
                        this.payoneer.checkoutList("paymentNetworks", {
                            payButton: "submitBtn",
                            payButtonContainer: "submitBtnContainer",
                            fullPageLoading: false,
                            listUrl: data.approve_url,
                            widgetCssUrl: window.location.origin + "/style/widget.css",
                            smartSwitch: true,
                            liveValidation: true,
                            cardView: false,
                            proceedFunction: (resultData) => {
                                const { interaction, resultInfo } = resultData
                                // https://checkoutdocs.payoneer.com/docs/zh-cn/create-an-immediate-payment-flow redirect包含重定向参数，及参数和请求方法等...
                                console.log('--------------- proceedFunction', resultData);
                                // 成功
                                if (interaction.code == 'PROCEED' && interaction.reason == 'OK') {
                                    this.dialog.substatus = 'polling'
                                    this.dialog.count = 15;
                                    this.doPayPolling()
                                } else {
                                    // 报告问题/让用户更正其输入
                                    this.dialog.substatus = 'failure'
                                    this.dialog.error = ''
                                }
                            },
                            onResult: (res) => {
                                console.log('--------------- onResult', res);
                            },
                            onBeforeCharge: () => {
                                // CHARGE 请求后立即成功
                                return true;
                            },
                            onBeforeServerError: (ctx) => {

                                console.log('--------------- onBeforeServerError', ctx);
                                // 服务器初始化错误
                                this.dialog = null;
                                this.$emit('statusChange', {
                                    payment: 'card',
                                    action: 'failure',
                                    message: ''
                                })
                            },
                        });

                        this.setParentStatus('paying')

                        this.addressBilling = billing.data || {};
                        this.addressList = address.data || [];
                        this.addressCurrent = JSON.parse(JSON.stringify(billing.data || {}))
                        this.approve_code = (data.approve_url.match(/([^\/]+)$/) || [])[0] || ''
                        this.dialog = dialog
                        this.ready = true;
                        this.checkTimeout();


                    }







                } else {
                    this.dialog = null;
                    this.$emit('statusChange', {
                        payment: 'card',
                        action: 'failure',
                        message: payoneer.msg || ''
                    })
                }
            })
        },

        // 点击确认支付按钮
        doPayButtonClick () {

            if (this.addressForbid) {
                // 禁用
            } else if (this.addressTab == 'default') {
                document.querySelector('#submitBtn').click()
            } else {
                const request = {
                    ...this.addressCurrent,
                    type: this.addressSave ? 1 : 2
                }
                delete request.id;

                console.log(this.approve_code);


                this.$http('Order.setPayoneerBilling/' + this.approve_code, request).then(res => {
                    if (res.code === 0) {
                        document.querySelector('#submitBtn').click()
                    } else {
                        this.dialog = null;
                        this.$emit('statusChange', {
                            payment: 'card',
                            action: 'failure',
                            message: res.msg || ''
                        })
                    }
                })
            }
        },

        // 轮询订单状态
        doPayPolling () {


            const allow = this.dialog && /polling|pending/.test(this.dialog.substatus)

            // 有dialog才轮询
            if (!allow) {
                // 中止
            } else if (this.dialog.count < 0) {
                // 次数过多
                this.dialog = null;
                this.$emit('statusChange', {
                    payment: 'card',
                    action: 'failure',
                    message: 'Paying polling timed out.'
                })

            } else {

                const option = {
                    payby: 'card',
                    action: this.option.action,
                    payment: 'payoneer',
                    codes: this.option.codes,
                    polldate: this.dialog.polldate,
                }
                PaymentUtils.checkPaymentStatus(option).then(info => {
                    if (!this.dialog) {
                        // 没有弹窗，不管了
                    } else if (info.status == 'success') {
                        // 成功
                        this.dialog = null;
                        this.$emit('statusChange', {
                            payment: 'card',
                            action: 'success',
                        })
                    } else if (info.status == 'failure') {
                        this.dialog = null;
                        this.$emit('statusChange', {
                            payment: 'card',
                            action: 'failure',
                            message: info.message
                        })
                    } else if (/polling|pending/.test(info.status)) {
                        // 支付中
                        this.dialog.substatus = info.status
                        this.dialog.count -= 1;
                        setTimeout(this.doPayPolling, 2000);
                    }

                }).catch(info => {
                    // 失败，网络请求等失败
                    if (this.dialog) {
                        this.dialog.count -= 1;
                        setTimeout(this.doPayPolling, 2000);
                    }
                })
            }
        },

        // 检查超时
        checkTimeout () {

            if (!this.dialog) {
                // 没有对话框不管
            } else if (new Date().getTime() >= this.dialog.timeout) {
                // 超时了
                this.dialog.substatus = 'timeout'

            } else {
                setTimeout(this.checkTimeout, 1000);
            }
        },

        // 加载资源库
        loadLib () {
            import('@payoneer/op-payment-widget-v3').then(module => {
                // 在客户端使用模块
                this.payoneer = module
            })
        }
    },
    created () {
        this.loadLib()
    },
    beforeDestroy () {
        this.dialog = null;
    },
}
</script>
<style lang="scss" scoped>
@-webkit-keyframes load7 {

    0%,
    80%,
    100% {
        box-shadow: 0 2.5em 0 -1.3em;
    }

    40% {
        box-shadow: 0 2.5em 0 0;
    }
}

@keyframes load7 {

    0%,
    80%,
    100% {
        box-shadow: 0 2.5em 0 -1.3em;
    }

    40% {
        box-shadow: 0 2.5em 0 0;
    }
}

.payment-payoneer {
    &>button {
        width: 100%;
        height: 48px;
        border-radius: 8px;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.3s;
        border: none;
        font-size: 16px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        line-height: 18px;
        color: #fff;
        background: #000;

        &:hover {
            // background: #ffa600;
            opacity: 0.6;
        }
    }

    &[disabled] button {
        user-select: none;
        background: #d8d8d8;
        color: #ffffff;
        pointer-events: none;
    }
}

.dialog-layout::v-deep {
    &>.dialog-content>h6 {
        display: none;
    }

    &>.dialog-content>.dialog-body {
        position: relative;
        overflow: hidden;
        display: flex;
        font-family: Roboto-Regular, Roboto;
    }
}

.order-payment-close {
    z-index: 1;
    position: absolute;
    right: 4px;
    top: 4px;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #555;
    transition: all 0.3s;
    cursor: pointer;
    border-radius: 4px;

    svg {
        width: 10px;
        height: 10px;
    }

    &:hover {
        background-color: rgba(255, 0, 0, 0.1);
        color: #8c1c14;
    }
}

.order-payment-input {
    width: calc(100vw - 80px);
    max-width: 600px;
    display: flex;
    flex-direction: column;
    padding: 20px 24px 0;
    box-sizing: border-box;

    &>h2 {
        line-height: 24px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        font-size: 18px;
        color: #292929;
        line-height: 24px;
        text-align: left;
        font-style: normal;
    }

    &>p {
        margin: 16px -24px 0;
        display: flex;
        align-items: center;
        justify-content: center;
        font-family: Roboto, Roboto;
        font-weight: 400;
        font-size: 12px;
        color: #548b5f;
        line-height: 32px;
        text-align: left;
        font-style: normal;
        background: #f4faf4;
        border-radius: 0px 0px 10px 10px;
        text-align: center;

        img {
            width: 14px;
            height: 14px;
            margin-right: 2px;
        }
    }

    .card-code {
        margin-top: 10px;
        height: 252px;
        background: #f6f6f6;
        border-radius: 6px;

        &>h3 {
            margin: 0 18px;
            height: 64px;
            border-bottom: 1px dashed #d1d1d1;
            display: flex;
            align-items: center;

            span {
                margin-left: 8px;
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;
                font-size: 14px;
                color: #292929;
                line-height: 20px;
            }

            img {
                width: 32px;
                height: 32px;
            }
        }

        &::v-deep .card-code-button {
            opacity: 0;
            pointer-events: none;
            position: absolute;
            left: -99em;
            top: -99em;
        }

        &::v-deep .payment-networks-container {
            display: flex;
            flex: 1;
            margin-top: -64px;

            .op-payment-widget-main-container {
                position: initial;
            }

            .loadingInContainer {
                display: flex;
                align-items: center;
                justify-content: center;

                .loading-container {
                    position: absolute;
                    z-index: 2;
                    background-color: rgba(255, 255, 255, 0.9);
                    margin: 0;
                    top: 0;
                    right: 0;
                    bottom: 0;
                    left: 0;
                    width: auto;
                    height: auto;
                    transition: opacity 0.2s;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                    pointer-events: none;
                    font-size: 10px;

                    svg {
                        display: none;
                    }

                    &,
                    &:before,
                    &:after {
                        border-radius: 50%;
                        width: 2.5em;
                        height: 2.5em;
                        -webkit-animation-fill-mode: both;
                        animation-fill-mode: both;
                        -webkit-animation: load7 1.8s infinite ease-in-out;
                        animation: load7 1.8s infinite ease-in-out;
                    }

                    & {
                        color: #f8cf1e;
                        margin: 0 auto;
                        position: relative;
                        top: -2.5em;
                        text-indent: -9999em;
                        -webkit-transform: translateZ(0);
                        -ms-transform: translateZ(0);
                        transform: translateZ(0);
                        -webkit-animation-delay: -0.16s;
                        animation-delay: -0.16s;
                    }

                    &:before,
                    &:after {
                        content: '';
                        position: absolute;
                        top: 0;
                    }

                    &:before {
                        left: -3em;
                        -webkit-animation-delay: -0.32s;
                        animation-delay: -0.32s;
                        color: #ea4c89;
                    }

                    &:after {
                        left: 3em;
                        color: #48c4ef;
                    }
                }
            }

            .op-payment-widget-container {
                position: initial;

                .imgLabel {
                    position: absolute;
                    right: 42px;
                    top: 82;
                    height: 64px;
                    display: flex;
                    align-items: center;
                    padding: 0;

                    img {
                        height: 22px;
                        min-width: 36px;
                        margin: 0;
                        background: #fff;
                        border: 1px solid #d6d6d6;
                        margin-left: 4px;
                        border-radius: 4px;
                    }
                }

                .textLabel {
                    display: none;
                }

                .available-network {
                    margin: 0;
                }

                .formContainer {
                    margin: 0;

                    iframe {
                        height: 252px;
                    }
                }
            }

            .op-payment-widget-full-loading {
                background-color: rgba(255, 255, 255, 0.8);
            }

            .test-indicator-badge {
                display: none;
            }
        }

        // &::v-deep .payment-networks-container {
        //     position: absolute;
        //     left: 0;
        //     top: 0;
        //     width: 100%;
        //     height: 100%;
        //     display: flex;
        //     flex: 1;
        // }

        // &::v-deep .op-payment-widget-full-loading {
        //     position: absolute;
        //     width: 100%;
        //     height: 100%;
        // }

        // &::v-deep .op-payment-widget-container {
        //     height: 100%;
        //     .formContainer {
        //         position: absolute;
        //         width: 100%;
        //         height: 252px;
        //         left: 0;
        //         top: 0;
        //         margin: 0px;
        //         iframe {
        //             width: 100%;
        //             height: 252px;
        //         }
        //     }
        // }

        &>.loading {
            background: none;
        }

        &[ready='true'] {
            &>.loading {
                display: none;
            }

            &>h3,
            &>iframe {
                visibility: visible;
            }
        }
    }

    .card-footer {
        display: flex;
        margin: 0 -24px;
        flex-direction: column;
        align-items: center;
        border-top: 1px solid #f0f0f0;

        button {
            width: 360px;
            height: 44px;
            margin: 16px auto 0;
            padding: 0;

            svg {
                width: 20px;
                height: 20px;
                vertical-align: top;
            }
        }

        &>span {
            width: 100%;
            box-sizing: border-box;
            padding: 7px 0;
            background: #f4faf4;
            line-height: 18px;
            text-align: center;
            font-size: 12px;
            font-weight: 400;
            color: #4b995a;
            border-radius: 0 0 10px 10px;

            img {
                width: 18px;
                height: 18px;
                vertical-align: top;
                margin-right: 4px;
            }
        }
    }

    &::v-deep>.el-loading-mask {
        pointer-events: all !important;
        z-index: 1 !important;
    }
}

.order-payment-jumpto,
.order-payment-timeout,
.order-payment-failure {
    width: 320px;
    height: 414px;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 0 auto;

    &>figure {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        img {
            width: 80px;
            height: 80px;
        }

        strong {
            margin: 16px 20px 0;
            font-size: 18px;
            color: #000000;
            line-height: 28px;
            text-align: center;
        }

        span {
            margin: 8px 20px;
            font-size: 14px;
            color: #555555;
            line-height: 18px;
            text-align: center;
            white-space: pre-wrap;
        }
    }

    &>button {
        height: 38px;
        line-height: 36px;
        width: 280px;
        margin-bottom: 30px;
        font-size: 14px;
    }
}

.order-payment-failure>figure image {
    width: 60px;
    height: 60px;
}

.order-payment-polling,
.order-payment-pending {
    width: 320px;
    height: 414px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    &>figure {
        width: 66px;
        height: 66px;

        img {
            width: 100%;
            height: 100%;
        }
    }

    &>h4 {
        height: 8px;
        margin-top: 16px;

        img {
            width: 40px;
            height: 8px;
        }
    }

    &>p {
        margin: 26px 20px 0;
        font-size: 20px;
        font-weight: bold;
        color: #000000;
        line-height: 24px;
        text-align: center;
    }
}
</style>
